import React, { Component } from 'react'
import { NavBar, Icon, Carousel, Toast } from "antd-mobile"
import myaxios from "../../utils/myaxios"
import "./goodDetail.scss"

export default class GoodDetail extends Component {
  constructor(props) {
    super(props)
    console.log(props)
  }
  state = {
    goodInfo: {},
    imgHeight: 250,
    /* 设置轮播图是否显示 默认情况不显示 */
    showSwiper: false,
    showCollect: false
  }

  componentDidMount() {

    let { goods_id } = this.props.match.params;
    myaxios
      .get("goods/detail", {
        params: {
          goods_id,
        },
      })
      .then((res) => {
        console.log(res);
        this.setState({
          goodInfo: res,
          showSwiper: true,
        });
      })
      .catch((err) => console.log(err));
    // 初次进入的时候需要判断是否需要缓存
    let collections_str = localStorage.getItem("collections");
    let collections = JSON.parse(collections_str || "[]")
    // 对收藏进行循环遍历
    let index = collections.findIndex(v => {
      // 判断是否在收藏中
      if (v.goods_id === parseInt(goods_id)) {
        return true
      }
    })
    if (index !== -1) {
      this.setState({
        showCollect: true
      })
    }
  }

  // 点击收藏
  handleCollect = (params) => {
    // 本地缓存是否有缓存
    // collections代表本地缓存的数据 数组
    let collections_str = localStorage.getItem("collections");
    let collections = JSON.parse(collections_str || "[]")
    // 对收藏进行循环遍历
    let index = collections.findIndex(v => {
      // 判断是否在收藏中
      if (v.goods_id === this.state.goodInfo.goods_id) {
        return true
      }
    })
    if (index !== -1) {
      // 代表已经缓存过
      collections.splice(index, 1)
      Toast.info("取消收藏成功", 1)
      this.setState({
        showCollect: false
      })

    } else {
      collections.push(this.state.goodInfo)
      Toast.info("收藏成功", 1)
      this.setState({
        showCollect: true
      })
    }
    localStorage.setItem("collections", JSON.stringify(collections))
  }
  gotoCart = (params) => {
    this.props.history.push("/cart")
  }
  // 添加到购物车
  addToCart = (params) => {
    //1.从本地缓存中拿去数据
    let carts_str = localStorage.getItem("carts");
    let carts = JSON.parse(carts_str || "[]")
    // 获取goods_id
    let { goods_id } = this.props.match.params;
    let index = carts.findIndex(v => {
      if (v.goods_id === parseInt(goods_id)) {
        return true
      }
    })
    if (index === -1) {
      let goods_info = this.state.goodInfo;
      goods_info.num = 1;//第一次添加数据
      goods_info.checked = true;//添加商品默认选中
      carts.push(goods_info)
    } else {
      carts[index].num ++ ;//第n次添加商品
    }
    localStorage.setItem("carts",JSON.stringify(carts))
  }
  // 支付函数
  pay=(params) => {
    this.props.history.push("/pay")
  }
  
  render() {
    return (
      <div className="yg-detail">
        {/* 导航栏开始 */}
        <NavBar mode="light"
          className="goodDetail-nav"
          icon={<Icon type="left" />}
          onLeftClick={() => window.history.go(-1)}
        >商品详情</NavBar>
        {/* 导航栏结束 */}

        {/* 详情页轮播图开始 */}
        <div className="yg-detail-swiper">
          {this.state.showSwiper && (
            <Carousel autoplay={true} infinite >
              {this.state.goodInfo.pics && this.state.goodInfo.pics.map((v) => {
                return (
                  <div
                    key={v.goods_id}
                    className="imageWrapper"
                    style={{
                      display: "inline-block",
                      width: "100%",
                      height: this.state.imgHeight,
                    }}
                  >
                    <img
                      src={v.pics_mid}
                      alt=""
                      style={{ width: "100%", verticalAlign: "top" }}
                      onLoad={() => {
                        // fire window resize event to change height
                        window.dispatchEvent(new Event("resize"));
                        this.setState({ imgHeight: "auto" });
                      }}
                    />
                  </div>
                )
              }
              )}
            </Carousel>
          )}
        </div>
        {/* 详情页轮播图结束 */}

        {/* 价格和分享开始 */}
        <div className="yg-detail-price">
          <div className="price-left">
            <span className="price-title">￥{this.state.goodInfo.goods_price}</span>
          </div>
          <div className="price-right">
            <i className="iconfont icon-fenxiang"></i>
            <i className={this.state.showCollect ? "iconfont icon-shoucang active" : "iconfont icon-shoucang"} onClick={this.handleCollect}></i>
          </div>
        </div>
        {/* 价格和分享结束 */}

        {/* 商品标题开始 */}
        <div className="yg-detail-title">
          {this.state.goodInfo.goods_name}
        </div>
        {/* 商品标题结束 */}

        {/* 商品详情开始 */}
        <div className="yg-detail-richtext">
          <div className="richtext-title">图片详情</div>
          <div className="richtext-content" dangerouslySetInnerHTML={{ __html: this.state.goodInfo.goods_introduce }}></div>
        </div>
        {/* 商品详情结束 */}

        {/* 底部工具栏开始 */}
        <div className="yg-detail-bottom">
          <div className="bottom-contact">
            <i className="iconfont icon-lianxikefu"></i>
            <div className="title">联系客服</div>
          </div>

          <div className="bottom-cart" onClick={this.gotoCart}>
            <i className="iconfont icon-gouwuche"></i>
            <div className="title" >购物车</div>
          </div>

          <div className="bottom-addCart" onClick={this.addToCart}>
            <span className="title1">加入购物车</span>
          </div>

          <div className="bottom-buy" onClick={this.pay}>
            <span className="title2">立即购买</span>
          </div>
        </div>
        {/* 底部工具栏结束 */}

      </div>
    )
  }
}
